/*
 * Copyright 2017 JessYan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.kmproject.haifu.app;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.jess.arms.http.GlobalHttpHandler;
import com.jess.arms.http.log.RequestInterceptor;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.mvp.model.entity.ResultBean;
import com.kmproject.haifu.mvp.model.entity.beans.UserLoginBean;
import com.kmproject.haifu.mvp.ui.activity.UserLoginActivity;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * ================================================
 * 展示 {@link GlobalHttpHandler} 的用法
 * <p>
 * Created by JessYan on 04/09/2017 17:06
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * ================================================
 */
public class GlobalHttpHandlerImpl implements GlobalHttpHandler {
    private Context context;

    public GlobalHttpHandlerImpl(Context context) {
        this.context = context;
    }

    /**
     * 这里可以先客户端一步拿到每一次 Http 请求的结果, 可以先解析成 Json, 再做一些操作, 如检测到 token 过期后
     * 重新请求 token, 并重新执行请求
     *
     * @param httpResult 服务器返回的结果 (已被框架自动转换为字符串)
     * @param chain      {@link Interceptor.Chain}
     * @param response   {@link Response}
     * @return
     */
    @Override
    public Response onHttpResultResponse(String httpResult, Interceptor.Chain chain, Response response) {
        try {
            if (httpResult != null) {
                Log.i("#######", httpResult + "");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
//        if (httpResult==null)
//        {
////            throw new ApiException("服务异常", 1001);
//            return response;
//        }
        if (!TextUtils.isEmpty(httpResult) && RequestInterceptor.isJson(response.body().contentType())) {
            try {
                JSONObject jsonObject = new JSONObject(httpResult);
                if (jsonObject.has("error") && jsonObject.get("error").equals("invalid_token") || (jsonObject.has("code") && jsonObject.getInt("code") == 2012)) {
                    //token过期，跳转到登录界面
                    DataHelper.removeSF(AppManager.getAppManager().getCurrentActivity(), AppConstant.LOGUSER_LOGIN_INFOIN);
                    if (!(AppManager.getAppManager().getCurrentActivity() instanceof UserLoginActivity))
                    {
                        ArmsUtils.startActivity(AppManager.getAppManager().getCurrentActivity(), UserLoginActivity.class);
                    }
                    throw new ApiException("登录超时，请重新登录", AppConstant.account_expired);
                } else {
                    ResultBean stringBaseResponse = ArmsUtils.obtainAppComponentFromContext(context).gson().fromJson(httpResult, ResultBean.class);
                    if (stringBaseResponse.getCode() == AppConstant.success) {
                        return response;
                    } else {
                        throw new ApiException(stringBaseResponse.getMessage(), stringBaseResponse.getCode());
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
//            Type type = new TypeToken<BaseResponse<String>>(){}.getType();
        }

        /* 这里如果发现 token 过期, 可以先请求最新的 token, 然后在拿新的 token 放入 Request 里去重新请求
        注意在这个回调之前已经调用过 proceed(), 所以这里必须自己去建立网络请求, 如使用 Okhttp 使用新的 Request 去请求
        create a new request and modify it accordingly using the new token
        Request newRequest = chain.request().newBuilder().header("token", newToken)
                             .build();

        retry the request

        response.body().close();
        如果使用 Okhttp 将新的请求, 请求成功后, 再将 Okhttp 返回的 Response return 出去即可
        如果不需要返回新的结果, 则直接把参数 response 返回出去即可*/
        return response;
    }

    /**
     * 这里可以在请求服务器之前拿到 {@link Request}, 做一些操作比如给 {@link Request} 统一添加 token 或者 header 以及参数加密等操作
     *
     * @param chain   {@link Interceptor.Chain}
     * @param request {@link Request}
     * @return
     */
    @Override
    public Request onHttpRequestBefore(Interceptor.Chain chain, Request request) {
        /* 如果需要再请求服务器之前做一些操作, 则重新返回一个做过操作的的 Request 如增加 Header, 不做操作则直接返回参数 request
        return chain.request().newBuilder().header("token", tokenId)
                              .build(); */
//        return request;
        UserLoginBean userBean = DataHelper.getDeviceData(context, AppConstant.LOGUSER_LOGIN_INFOIN);
        String temAccess_toke = "";
        String token_type = "";
        if (userBean != null && !TextUtils.isEmpty(userBean.getAccess_token())) {
            temAccess_toke = userBean.getAccess_token();
            token_type = userBean.getToken_type();
        }

        FormBody.Builder builder = new FormBody.Builder();
        RequestBody requestBody = request.body();
        if (requestBody instanceof FormBody) {
            FormBody formBody = (FormBody) requestBody;
            for (int i = 0; i < formBody.size(); i++) {
                builder.add(formBody.name(i), formBody.value(i));
                Log.i("#######pamear", formBody.value(i));
            }
            return request.newBuilder().addHeader("Authorization", token_type + " " + temAccess_toke).addHeader("deviceId", AppUtil.getIMEI(AppManager.getAppManager().getCurrentActivity())).url(request.url()).post(builder.build()).build();
        } else if (requestBody instanceof MultipartBody) {
            return request.newBuilder().addHeader("Authorization", token_type + " " + temAccess_toke).addHeader("deviceId", AppUtil.getIMEI(AppManager.getAppManager().getCurrentActivity())).url(request.url()).post(requestBody).build();
        }
        return request.newBuilder().addHeader("Authorization", token_type + " " + temAccess_toke).addHeader("deviceId", AppUtil.getIMEI(AppManager.getAppManager().getCurrentActivity())).url(request.url().newBuilder().build()).build();
//          return request.newBuilder().addHeader("Authorization",token_type+" "+temAccess_toke).url(request.url()).post(builder.build()).build();
    }
}
